import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { RoleService } from 'src/app/services/role.service';
import { ActivatedRoute, Router } from '@angular/router';  // 用于获取路由参数
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { PersonnelService } from 'src/app/services/personnel.service';
import { DepartmentService } from 'src/app/services/department.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { PersonnelModalComponent } from 'src/app/pages/companyInfo/organization/details-organization/personnel-modal/personnel-modal.component';
import { DepartmentModalComponent } from 'src/app/pages/companyInfo/organization/details-organization/department-modal/department-modal.component';
import { AccountModalComponent } from 'src/app/pages/companyInfo/organization/details-organization/account-modal/account-modal.component';
import { JurisdictionModalComponent } from 'src/app/pages/companyInfo/organization/details-organization/jurisdiction-modal/jurisdiction-modal.component';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
@Component({
  selector: 'zepride-drawer-modal',
  templateUrl: './drawer-modal.component.html',
  styleUrls: ['./drawer-modal.component.less']
})
export class DrawerModalComponent implements OnInit {
  @Input() UserInfo;
  @Input() TreeInfo;
  @Input() treeList;
  @Input() id = '';
  @Input() orgTreeId = '';
  @Input() presentId = '';
  @Input() objectName = '';
  @Input() superiorId = '';
  @Output() refresh: EventEmitter<any> = new EventEmitter<any>();
  permitssList = [];
  AccountPermitsList = []; //添加人员权限
  isJurisdictionVisible = false;
  constructor(
    private msg: NzMessageService,
    private route: Router,
    private roleService: RoleService,
    private modal: NzModalService,
    private personnelService: PersonnelService,
    private departmentService: DepartmentService,
    private organizationService: OrganizationService,
  ) { }

  ngOnInit(): void {
  }
  showModal(type) {
    if (type == 'personnel') {
      const modelRef = this.modal.create({
        nzTitle: `添加【${this.TreeInfo.name}】下的人员`,
        nzContent: PersonnelModalComponent,
        nzFooter: null,
        nzComponentParams: {
          organizationId: this.id,
          presentId: this.presentId,
          treeList: this.treeList
        }
      });
      modelRef.afterClose.subscribe((result) => {
        if (result) {
          this.refresh.emit();
        }
      });
    } else if (type == 'department') {
      const modelRef = this.modal.create({
        nzTitle: `添加【${this.TreeInfo.name}】下的子部门`,
        nzContent: DepartmentModalComponent,
        nzFooter: null,
        nzComponentParams: {
          organizationId: this.id,
          notequId: this.TreeInfo.id,
          presentId: this.presentId,
          treeList: this.treeList
        }
      });
      modelRef.afterClose.subscribe((result) => {
        if (result) {
          this.refresh.emit();
        }
      });
      //人员弹窗
    } else if (type == 'account') {
      this.modal.create({
        nzTitle: '修改账号信息',
        nzContent: AccountModalComponent,
        nzFooter: null,
        nzComponentParams: {
          UserInfo: this.UserInfo,
          orgTreeId: this.orgTreeId
        }
      });
      //权限弹窗
    } else {
      this.queryAccountPermitss();
    }

  }

  isCheckAll(permitssList) {
    permitssList.checked = permitssList.value.every(v => v.checked);
  }

  //角色权限
  async queryAccountPermitss() {
    try {
      const data = await this.roleService.queryAccountPermitss({ authObjectId: this.UserInfo.accountId, authObjectType: 'User' });
      //newArr 添加状态
      const newArr = data.permitConfig.map(v => {
        return { ...v, checked: false }
      })
      // //判断list 是否有值，有值代表有权限
      if (data.list.length) {
        data.permitConfig.filter(p => {
          data.list.find(i => {
            if (p.permitId == i.permitId) {
              return p.checked = true;
            }
          })
        })
        //插入保存数据this.roleParams.permits
        this.AccountPermitsList = data.list.map(v => {
          return {
            permitId: v.permitId,
            permitName: v.permitName,
            authObjectId: this.UserInfo.accountId,
            authObjectType: 'User'
          }
        })
      }
      // 遍历数据格式
      const result = [];
      data.permitConfig.forEach((item) => {
        var { groupName } = item;
        if (!result[groupName]) {
          result[groupName] = {
            groupName,
            checked: false,
            value: []
          }
        }
        result[groupName].value.push({ permitId: item.permitId, permitName: item.permitName, checked: item.checked });
      });

      this.permitssList = Object.values(result);
      this.permitssList.forEach(element => {
        this.isCheckAll(element);
      });
      this.modal.create({
        nzTitle: '人员权限',
        nzContent: JurisdictionModalComponent,
        nzFooter: null,
        nzComponentParams: {
          permitssList: this.permitssList,
          accountId: this.UserInfo.accountId
        }
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  clickdel(id, name, type) {
    //删除部门判断部门下是否有人员
    if (type == 'Department') {
      // this.refresh.emit();
      this.getOrganizationTrees('User', this.presentId, id);
    } else {
      this.modal.confirm({
        nzTitle: `您确定要删除【${name}】么?`,
        nzOnOk: () => {
          this.deleteUser(id);
        },
        nzMask: false
      });
    }
  }
  //查询树下面得 子集部门
  async getOrganizationTrees(objectName, parentId, id) {
    const params = {
      objectName: '',
      parentId: ''
    };
    try {
      const data = await this.organizationService.getOrganizationTrees(params);
      if (this.objectName) {
        this.modal.confirm({
          nzTitle: data.length ? '您确定删除部门及所有子级部门和用户吗？' : `您确定要删除<b style="color: red;">${name}</b>么?`,
          nzOnOk: () => {
            this.delDepartment(id);
          },
          nzMask: false
        });
      }

    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  //删除人员
  async deleteUser(id) {
    try {
      await this.personnelService.deleteUser(id);
      this.msg.success('删除人员成功');
      this.refresh.emit();
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  //删除部门接口
  async delDepartment(id) {
    try {
      await this.departmentService.deleteDepartment(id);
      this.refresh.emit();
      this.msg.success('删除部门成功');
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }
  //跳转页面
  clickskip(url, type) {
    //列表
    if (type == 'list') {
      this.route.navigateByUrl(url);
      //编辑
    } else if (type == 'add') {
      this.route.navigate([url], { queryParams: { Id: 0, organizationId: this.id, parentId: this.presentId } });
    } else if (type == 'uplevel') {
      this.route.navigate([url], { queryParams: { Id: this.TreeInfo.id, notequId: this.TreeInfo.id, parentId: this.superiorId } });
    } else if (type == 'upUser') {
      this.route.navigate([url], { queryParams: { Id: this.UserInfo.id, parentId: this.presentId } });
    } else {
      this.route.navigate([url], { queryParams: { Id: this.id } });
    }
  }
}
